<template>
  <!-- Preloader Start -->
  <!-- <div class="preloader">
    <img src="assets/images/preloader.svg" alt="preloader" />
  </div> -->
  <!-- Preloader End -->
  <!-- Header Start -->
  <header class="header can-sticky">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <div class="inner">
            <!-- Logo -->
            <div class="logo">
              <a @click="router.push('/')" class="d-flex h-100">
                <img src="../assets/images/logo-3.png" alt="logo" class="image-fit-contain" />
              </a>
            </div>
            <!-- Logo -->
            <!-- Nav -->
            <TheNavigation :class="['navigation', { open: isMenuOpen }]" />
            <!-- Nav -->
            <MobileNav v-model="isMenuOpen" />
          </div>
        </div>
      </div>
    </div>
  </header>
  <!-- Header End -->
  <!-- Subheader Start -->
  <div class="section-bg section-padding subheader" :style="{ backgroundImage: `url(${subheader})` }">
    <div class="container">
      <div class="row">
        <div class="col-12 text-center">
          <h2 class="text-white page-title">{{ t("nav.organization") }}</h2>
        </div>
      </div>
    </div>
  </div>
  <!-- Subheader End -->
  <!-- About Start -->
  <section class="section-padding section" id="intro">
    <div class="container">
      <div class="row align-items-center">
        <div class="col-lg-6">
          <div class="image mb-xl-30">
            <img :src="introInfo.image_url" alt="img" class="image-fit" />
          </div>
        </div>
        <div class="col-lg-6">
          <div class="section-header">
            <h3 class="title">{{ t("nav.organization_intro") }}</h3>
          </div>
          <p>
            {{ introInfo.content }}
          </p>
        </div>
      </div>
    </div>
  </section>
  <!-- About End -->
  <!-- Testimonials Start -->
  <section class="section-padding thm-bg-light" id="leaders">
    <div class="container">
      <div class="section-header">
        <h3 class="title">{{ t("nav.organization_leaders") }}</h3>
      </div>
      <div class="row testimonial_slider" v-if="leadList.length">
        <div class="col-12" v-for="item in leadList" :key="item.id">
          <div class="testimonial_item">
            <div class="testimonial_image">
              <img :src="item.avatar" :alt="item.name" class="image-fit" />
            </div>
            <div class="testimonial_text">
              <h4 class="title">{{ item.name }}</h4>
              <p class="post">{{ item.position }}</p>
              <div v-html="item.content" class=""></div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="text-center text-gray-500 py-6">暂无数据</div>
    </div>
  </section>
  <!-- Testimonials End -->
  <!-- Team Start -->
  <section class="section-padding section" id="advisors">
    <div class="container">
      <div class="section-header text-center">
        <h3 class="title">{{ t("nav.organization_advisors") }}</h3>
      </div>
      <div class="row">
        <div class="col-lg-3 col-md-6" v-for="item in expertList" :key="item.id">
          <div class="team_block">
            <div class="team_img">
              <img :src="item.avatar" :alt="item.name" class="image-fit" />
            </div>
            <div class="team_caption">
              <h5 class="team_name">
                <NuxtLink :to="`/expertDetail/${item.id}`">{{ item.name }}</NuxtLink>
              </h5>
              <p class="team_post">{{ item.position }}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="text-center mt-4">
        <button v-if="hasMore" class="thm-btn" :disabled="loading" @click="loadMore">
          {{ loading ? "加载中…" : "加载更多" }}
        </button>
        <p v-else class="text-muted">没有更多了</p>
      </div>
    </div>
  </section>

  <section class="section-padding section thm-bg-light" id="structure">
    <div class="container">
      <div class="section-header text-center">
        <h3 class="title">{{ t("nav.organization") }}</h3>
      </div>
      <div class="row">
        <div v-for="item in orgState.list" :key="item.id" class="col-lg-3 col-md-6">
          <div class="team_block">
            <div class="team_img mb-0">
              <img :src="item.avatar" alt="机构图片" class="image-fit" />
            </div>
            <!-- <div class="team_caption">
              <h5 class="team_name">
                <a href="javascript:void(0)">{{ item.name }}</a>
              </h5>
              <p class="team_post">{{ item.type }}</p>
            </div> -->
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-12">
          <nav>
            <ul class="pagination">
              <li class="page-item" :class="{ disabled: orgState.current_page === 1 }">
                <a class="page-link" href="javascript:void(0)" aria-label="Previous" @click.prevent="goTo(orgState.current_page - 1)">
                  <span aria-hidden="true">«</span>
                  <span class="sr-only">Previous</span>
                </a>
              </li>
              <li v-for="p in pages" :key="String(p)" class="page-item" :class="{ active: p === orgState.current_page, disabled: p === '…' }">
                <span v-if="p === '…'" class="page-link">…</span>
                <a v-else class="page-link" href="javascript:void(0)" @click.prevent="goTo(p as number)">{{ p }}</a>
              </li>
              <!-- Next -->
              <li class="page-item" :class="{ disabled: orgState.current_page === totalPages }">
                <a class="page-link" href="javascript:void(0)" aria-label="Next" @click.prevent="goTo(orgState.current_page + 1)">
                  <span aria-hidden="true">»</span>
                  <span class="sr-only">Next</span>
                </a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </section>
  <!-- Team End -->
  <!-- Footer Start -->
  <TheFooter />

  <!-- Footer End -->
  <!-- Copyright Start -->
  <div class="thm-bg-color-one copyright">
    <div class="container">
      <div class="row">
        <div class="col-12 text-center">
          <p class="mb-0">
            Copyright © <span id="year"></span>.
            <a target="_blank" href="#" title=" 科技创新院" class="text-white"> 科技创新院</a>
          </p>
        </div>
      </div>
    </div>
  </div>
  <!-- Copyright End -->
  <a href="#" data-target="html" class="back-to-top ft-sticky" style="">
    <i class="fal fa-long-arrow-up"></i>
  </a>
</template>

<script setup lang="ts">
import subheader from "../assets/images/subheader.jpg";
import TheNavigation from "../component/TheNavigation.vue";
import TheFooter from "~/component/TheFooter.vue";
import MobileNav from "~/component/MobileNav.vue";
import { getFetchData } from "~/composables/getData";

const { t } = useI18n();
const { public: pub } = useRuntimeConfig();
const route = useRoute();

useSeoMeta({
  title: "组织机构",
  description: "了解西班牙科技创新院的院况介绍、领导集体、专家顾问与组织架构。",
  ogUrl: pub.siteUrl + route.fullPath,
  ogImage: pub.defaultOG,
});

useHead({
  script: [
    {
      type: "application/ld+json",
      children: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "AboutPage",
      }),
    },
    {
      // Breadcrumb
      type: "application/ld+json",
      children: JSON.stringify({
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        itemListElement: [
          { "@type": "ListItem", position: 1, name: "首页", item: pub.siteUrl },
          { "@type": "ListItem", position: 2, name: "组织机构", item: pub.siteUrl + "/organization" },
        ],
      }),
    },
  ],
});
const router = useRouter();
const isMenuOpen = ref(false);

// 获取院况信息
const introInfo = ref<any>({});

// 获取院况信息
const getIntroInfo = async () => {
  try {
    const res: any = await getFetchData({
      url: "/api/college_get",
      method: "get",
    });
    introInfo.value = res?.data[0] || {};
  } catch (error) {
    console.log(error);
  }
};

await getIntroInfo();

// 获取院领导
const leadList = ref<any>([]);

const leadRes: any = await getFetchData({
  url: "/api/lead_get_list",
});
leadList.value = leadRes.data.data || [];

// 获取专家顾问
const expertList = ref<any[]>([]);
const page = ref(1);
const pageSize = 4;
const loading = ref(false);
const hasMore = ref(true);

async function fetchExperts(reset = false) {
  loading.value = true;
  try {
    const res: any = await getFetchData({
      url: "/api/expert_get_list",
      opts: { page_index: page.value, page_limit: pageSize },
      method: "get",
    });

    const list = res.data.data;

    if (reset) expertList.value = [];
    expertList.value = reset ? list : expertList.value.concat(list);

    // 依据 total 判断是否还有更多；没有 total 就用“返回数量 < pageSize”判断
    if (typeof res?.data?.total === "number") {
      const total = res.data.total as number;
      hasMore.value = expertList.value.length < total;
    } else {
      hasMore.value = list.length === pageSize;
    }

    if (hasMore.value) page.value += 1;
  } finally {
    loading.value = false;
  }
}

await fetchExperts(true);

function loadMore() {
  if (!loading.value && hasMore.value) fetchExperts();
}

const orgState = reactive({
  list: [] as any[],
  page_index: 1,
  page_limit: 8,
  loading: false,
  hasMore: true,
  last_page: 1,
  current_page: 1,
  total: 0,
});

const totalPages = computed(() => orgState.last_page || Math.max(1, Math.ceil(orgState.total / (orgState.page_limit || 1))));

// 生成页码（含省略号）
const pages = computed<(number | "…")[]>(() => {
  const total = totalPages.value;
  const curr = orgState.current_page;
  const delta = 2; // 当前页左右各展示几个
  if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);

  const range = new Set<number>([1, total]);
  for (let i = Math.max(1, curr - delta); i <= Math.min(total, curr + delta); i++) {
    range.add(i);
  }
  const arr = Array.from(range).sort((a, b) => a - b);
  const out: (number | "…")[] = [];
  for (let i = 0; i < arr.length; i++) {
    out.push(arr[i]);
    if (i < arr.length - 1 && arr[i + 1] - arr[i] > 1) out.push("…");
  }
  return out;
});

async function fetchOrg(page_index: number) {
  orgState.loading = true;
  try {
    const res: any = await getFetchData({
      url: "/api/jigou_get_list",
      opts: { page_index, page_limit: orgState.page_limit },
      method: "get",
    });
    const list = res.data.data;
    orgState.list = list;
    // 依据 total 判断是否还有更多；没有 total 就用“返回数量 < pageSize”判断
    if (typeof res?.data?.total === "number") {
      const total = res.data.total as number;
      orgState.hasMore = orgState.list.length < total;
    } else {
      orgState.hasMore = list.length === orgState.page_limit;
    }

    // if (orgState.hasMore) orgState.page_index += 1;
    orgState.last_page = res.data.last_page;
    orgState.current_page = res.data.current_page;
    orgState.total = res.data.total;
  } finally {
    orgState.loading = false;
  }
}

await fetchOrg(orgState.page_index);

async function goTo(page: number) {
  if (page < 1 || page > totalPages.value || page === orgState.current_page) return;
  await fetchOrg(page);
}

onMounted(() => {
  if (window.$ && $(".testimonial_slider").slick) {
    $(".testimonial_slider").slick({
      autoplay: true,
      dots: true,
      arrows: false,
    });
  }
});
</script>

<style></style>
